home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / mm / mm-0.90 / whoami.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-12-18  |  2.1 KB  |  82 lines

  1. /*
  2.  * Copyright (c) 1986, 1990 by The Trustees of Columbia University in
  3.  * the City of New York.  Permission is granted to any individual or
  4.  * institution to use, copy, or redistribute this software so long as it
  5.  * is not sold for profit, provided this copyright notice is retained.
  6.  */
  7.  
  8.  
  9. #ifndef lint
  10. static char *rcsid = "$Header: /f/src2/encore.bin/cucca/mm/tarring-it-up/RCS/whoami.c,v 2.1 90/10/04 18:27:01 melissa Exp $";
  11. #endif
  12.  
  13. /* 
  14.  * whoami - return the user's login name
  15.  * 
  16.  * In order to handle the situation where several login names map to the
  17.  * same uid, the USER and LOGNAME environment variables, and the
  18.  * /etc/utmp file are consulted for a name with a uid matching that
  19.  * returned by getuid().  If that fails, the first entry in the passwd
  20.  * database with a matching uid is returned.
  21.  * 
  22.  * If no name matching the current uid is found, NULL is returned.
  23.  */
  24.  
  25. #include "config.h"
  26. #include "osfiles.h"
  27. #include "compat.h"
  28. #include <pwd.h>
  29.  
  30. char *getenv (), *getlogin ();
  31. struct passwd *getpwnam (), *getpwuid ();
  32.  
  33. static char *envariables[] = { "USER", "LOGNAME" };
  34.  
  35. char *
  36. whoami ()
  37. {
  38.     int i;
  39.     char *cp;
  40.     struct passwd *pw;
  41.     static int realuid = -1;        /* user's real uid */
  42.     static char realname[64];        /* user's name */
  43.     char loginname[256], envname[256];
  44.  
  45.     if (realuid != -1)
  46.     return realname;
  47.  
  48.     realuid = getuid ();           /* get our uid */
  49.  
  50.     /*
  51.      * Check the conventional environment variables...
  52.      */
  53.     for (i = 0; i < sizeof envariables / sizeof envariables[0]; i++)
  54.     if (cp = getenv (envariables[i]))
  55.         if (pw = getpwnam (cp))
  56.         if (pw->pw_uid == realuid) {
  57.             strcpy (realname, cp);
  58.             return realname;
  59.         }
  60.  
  61.     /*
  62.      * See if there is an entry in the utmp file...
  63.      */
  64.     if (cp = getlogin ())
  65.     if (pw = getpwnam (cp))
  66.         if (pw->pw_uid == realuid) {
  67.         strcpy (realname, cp);
  68.         return (realname);
  69.         }
  70.  
  71.     /*
  72.      * Finally, look for the first maching entry in the passwd file.
  73.      */
  74.     if (pw = getpwuid (realuid)) {
  75.     strcpy (realname, pw->pw_name);
  76.     return realname;
  77.     }
  78.  
  79.     realuid = -1;
  80.     return NULL;
  81. }
  82.